package com.taomu.app.zongchouhuli.http.api;


import android.app.Application;
import android.widget.Toast;


import com.taomu.app.zongchouhuli.http.contract.RxJavaBaseCallback;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

import io.reactivex.observers.DefaultObserver;

/**
 * @author qiao
 * @date 2017/12/29 下午 2:54
 */

public class ExceptionObserver<T> extends DefaultObserver<T> {
    private RxJavaBaseCallback<T> mCallback;
    private Application application;

    public ExceptionObserver(RxJavaBaseCallback<T> callback, Application application) {
        mCallback = callback;
        this.application=application;
    }

    @Override
    public void onStart(){
        super.onStart();
        if (mCallback!=null){
            mCallback.onStart();
        }
    }

    @Override
    public void onNext(T t) {
        if(mCallback != null){
            mCallback.onNext(t);
        }
    }

    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
        if (e instanceof SocketTimeoutException) {
            Toast.makeText(application, "网络中断，请检查您的网络状态", Toast.LENGTH_SHORT).show();
        } else if (e instanceof ConnectException) {
            Toast.makeText(application, "网络中断，请检查您的网络状态", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(application, e.getMessage(), Toast.LENGTH_SHORT).show();
        }
        if(mCallback != null){
            mCallback.onComplete();
        }
    }

    @Override
    public void onComplete() {
        if (mCallback !=null){
            mCallback.onComplete();
        }
    }
}
